import axios from 'axios';
import { Message, MessageBox, Notification } from "element-ui";
import errorCode from './errorCode';

axios.defaults.headers["Content-Type"] = "application/json;charset=UTF-8";

const instance = axios.create({
  baseURL: 'http://192.168.1.102:8099', // 设置基础 URL
  timeout: 5000, // 设置超时时间
});

// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    // 可以在这里添加一些请求前的处理，如添加请求头
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    console.log(response)
    const code = response.data.code||200
    // 获取错误信息
    const msg = errorCode[code] || response.data.msg || errorCode['default']
    if(code === 401){
      MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(()=>{
        console.log('跳转登录页')
      })
    }else if(code === 500){
      Message({
        message: msg,
        type: 'error'
      })
      return Promise.reject(new Error(msg))
    }else if(code !== 200){
      Notification.error({
        title: msg
      })
      return Promise.reject('error')
    }else{
      return response.data
    }
  },
  error => {
    let {message} = error
    if(message == "Network Error"){
      message = "后端接口连接异常"
    }else if(message.includes("timeout")){
      message = "系统接口请求超时"
    }else if(message.includes("Request failed with status code")){
      message = "系统接口"+message.substr(message.length-3)+"异常"
    }
    Message({
      message: message,
      type: 'error',
      duration: 5*1000
    })
    // 对响应错误进行处理
    return Promise.reject(error);
  }
);

export default instance;
